package cn.school.classManage.service.impl;

import cn.school.classManage.dao.SchoolDormitoryDao;
import cn.school.classManage.service.SchoolDormitoryService;
import cn.school.classManage.vo.SchoolDormitoryVO;
import cn.school.common.utils.SysUserUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SchoolDormitoryServiceImpl extends ServiceImpl<SchoolDormitoryDao, SchoolDormitoryVO> implements SchoolDormitoryService {

    @Autowired
    private SchoolDormitoryDao schoolDormitoryDao;

    @Override
    public IPage<SchoolDormitoryVO> findSchoolDormitoryPageList(SchoolDormitoryVO vo) {
        int count = schoolDormitoryDao.findSchoolDormitoryPageListCount(vo);
        int startNum=(vo.getPageNum()-1)*vo.getPageSize();
        vo.setPageNum(startNum);
        List<SchoolDormitoryVO> commentList =  schoolDormitoryDao.findSchoolDormitoryPageList(vo);
        IPage<SchoolDormitoryVO> page = new Page<>();
        page.setTotal(count);
        page.setRecords(commentList);
        return page;
    }

    @Override
    public int addOrUpdateDormitory(SchoolDormitoryVO vo) {
        LambdaQueryWrapper<SchoolDormitoryVO> wrapper = new LambdaQueryWrapper<>(vo);
        wrapper.eq(SchoolDormitoryVO::getDormitoryNo,vo.getDormitoryNo());
        wrapper.eq(SchoolDormitoryVO::getBuildingNo,vo.getBuildingNo());
        wrapper.eq(SchoolDormitoryVO::getStorey,vo.getStorey());
        String username = SysUserUtils.getSysUser().getUsername();
        int flag = 0;
        if(StringUtils.isEmpty(vo.getId())){
            Integer num  = schoolDormitoryDao.selectCount(wrapper);
            if(num>0){
                return -1;//宿舍号重复
            }
            vo.setCreateTime(new Date());
            vo.setCreateBy(username);
            flag = schoolDormitoryDao.insert(vo);
        }else{
            wrapper.ne(SchoolDormitoryVO::getId,vo.getId());
            Integer num  = schoolDormitoryDao.selectCount(wrapper);
            if(num>0){
                return -1;//宿舍号重复
            }
            vo.setModifyTime(new Date());
            vo.setModifyBy(username);
            flag = schoolDormitoryDao.updateById(vo);
        }
        return flag;
    }

    @Override
    public int deleteDormitoryById(Long id) {
        return schoolDormitoryDao.deleteById(id);
    }
}
